import { loginApi, getUserInfoApi, getDetailUserInfoApi } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, payload) {
      // 存入state
      state.token = payload
      // 存入cookie实现持久化
      setToken(payload)
    },
    // 设置用户信息
    setUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除用户信息
    reomveUserInfo(state) {
      state.userInfo = {}
    },
    // 清除token
    removeToken(state) {
      state.token = null
      removeToken()
    }
  },
  actions: {
    async loginAction(context, data) {
      //发送请求
      const res = await loginApi(data)
      //触发mutation
      context.commit('setToken', res)
    },
    //获取用户资料Action
    async getUserInfoAction(context) {
      const res = await getUserInfoApi()
      //获取用户详细资料
      const res2 = await getDetailUserInfoApi(res.userId)
      context.commit('setUserInfo', { ...res, ...res2 })
    },
    // 退出操作
    quitAction(context) {
      //清除token
      context.commit('removeToken')
      //清除用户资料
      context.commit('reomveUserInfo')
    }
  }
}
